﻿/*
---------------------------------------------------------------------
http://sp.korablik.local/report/SitePages/Онлайн%20продажи.aspx
---------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Runtime.Serialization.Json;
using System.Windows.Threading;

namespace KoRepOnlineSales2
{
    public partial class MainPage : UserControl
    {

        #region Members

        List<dsData> list = new List<dsData>();
        private DispatcherTimer myTimer = new DispatcherTimer();
        public float mFooter = 0;
        int mStatus = 0;
        int saleCount = 0;

        #endregion

        public MainPage()
        {
            InitializeComponent();
            dataGrid1.ItemsSource = list;      
            dataGrid1.AutoGenerateColumns = false;
            mainFooter.Text = mFooter.ToString("C");
            
            //--
            SelectDate.DisplayDate = DateTime.Today; //DateTime.Now;
            SelectDate.Text = DateTime.Today.ToString();
            //--
            mStatus = 0;
            //--
            //myTimer.Interval = new TimeSpan(0,0,300);
            //myTimer.Tick += new EventHandler(myTimer_Tick);
            //myTimer.Start();
            
            
            //--
            //StartSaleUpdate();
            //--

            GetListShops();
        }

        void myTimer_Tick(object sender, EventArgs e)
        {
            StartSaleUpdate();
        }

        void StartSaleUpdate()
        {
            if (mStatus == 0)
            {
                //--
                SolidColorBrush mySolidColorBrush = new SolidColorBrush();
                mySolidColorBrush.Color = HexColor("#FF0000");
                RecStatus.Fill = mySolidColorBrush;
                //--
                mStatus = 1;
                saleCount = 0;
                //int mCount = 10;
                foreach (dsData mRow in list)
                {
                    //if (mCount > 0)
                    //{
                        GetSaleFromShopID(mRow.id);
                        saleCount++;
                    //}
                    //mCount--;
                }
                //mStatus = 0;
            }
        }

        void GetListShops()
        {
            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);

            WebClient wc = new WebClient();
            wc.UseDefaultCredentials = false;
            //wc.Credentials = new NetworkCredential("WebServiceUser", "Password", "APP18");
            wc.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");
            wc.UseDefaultCredentials = false;

            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(load_Shops);

            mFooter = 0;
            DateTime dt = DateTime.Now;
            if(SelectDate.SelectedDate!=null)
                dt = SelectDate.SelectedDate.Value;
            int Year = dt.Year, Month = dt.Month, Day = dt.Day;
            string dateStr = String.Format("?dt={0,4:0000}-{1,2:00}-{2,2:00}", Year, Month, Day);

            Uri myUri =
                //new Uri(@"http://sp.korablik.local/SitePages/ws/Data/Reports/ShopOnlineAmounts.aspx" + dateStr
                new Uri(@"http://sp.korablik.local:88/ws/ws.aspx" + dateStr
                    , UriKind.Absolute);

            wc.DownloadStringAsync(myUri);
        }

        void load_sale(object sender, DownloadStringCompletedEventArgs e)
        {
            //--
            saleCount--;
            if (saleCount == 0)
            {
                SolidColorBrush mySolidColorBrush = new SolidColorBrush();
                mySolidColorBrush.Color = HexColor("#FFFFFF");
                RecStatus.Fill = mySolidColorBrush;
                //--
                mStatus = 0;
                //--
                string uTime = DateTime.Now.ToString();
                UpdateTime.Text = uTime.Substring(11, 8);
                //--
            }
            //--
            if (e.Error != null)
            {
                MessageBox.Show("Error" + e.Error.Message);
                return;
            }

            XDocument grbs = XDocument.Parse(e.Result);
            var query = from g in grbs.Descendants("grb")
                        select new
                        {
                            grbId = (int)g.Element("grb_id"),
                            kassa1 = (float)g.Element("cash_1"),
                            kassa2 = (float)g.Element("cash_2"),
                            kassa3 = (float)g.Element("cash_3"),
                            kassa4 = (float)g.Element("cash_4")
                        };

            foreach (var grb in query)
            {
                int mID = grb.grbId;
                foreach (dsData mRow in list)
                {
                    if (mRow.id == mID)
                    {
                        mRow.kassa1 = grb.kassa1;
                        mRow.kassa2 = grb.kassa2;
                        mRow.kassa3 = grb.kassa3;
                        mRow.kassa4 = grb.kassa4;
                        mRow.total = grb.kassa1 + grb.kassa2 + grb.kassa3 + grb.kassa4;
                    }
                }
            }
            RefreshGrid();
            RefreshFooter();
        }

        void GetSaleFromShopID(int tID)
        {
            //DateTime mDate = SelectDate.DisplayDate;
            //MessageBox.Show(mDate.ToString());
            
            WebClient wbcl = new WebClient();
            wbcl.DownloadStringCompleted += new DownloadStringCompletedEventHandler(load_sale);
            Uri myUri = new Uri("http://portal.korablik.local/test/sl_sale_id.php?id=" + tID.ToString() + "&date=" + SelectDate.Text, UriKind.Absolute);
            wbcl.DownloadStringAsync(myUri);
            
        }

        void RefreshFooter()
        {
            float mSum = 0;
            foreach (dsData mRow in list)
            {
                mSum += mRow.total;
            }
            mainFooter.Text = ReturnNumericStringFormat(mSum);
        }

        string ReturnNumericStringFormat(float mFloat)
        {
            //string tTemp1 = mFloat.ToString();
            string tTemp1 = String.Format("{0:0.00}",mFloat);
            int tLen = tTemp1.Length;
            int tCount = (tLen - 3) / 3;
            if ((tLen - 3 - 3 * tCount) == 0) tCount--;
            int tStart = tLen - 3 - 3 * tCount;
            string tRet = tTemp1.Substring(0, tStart);
            for (int i = 0; i < tCount ; i++)
            {
                tRet += "`";
                tRet += tTemp1.Substring(tStart + i*3, 3);
            }
            tRet += tTemp1.Substring(tStart + tCount * 3, 3);
            return tRet;
        }

        void RefreshGrid()
        {
            PagedCollectionView taskListView = new PagedCollectionView(list);
            dataGrid1.ItemsSource = taskListView; 
        } 

        void AddLineTest(String mStr)
        {
            dsData newDataRecord;
            newDataRecord = new dsData();
            newDataRecord.ShopName = mStr;
            list.Add(newDataRecord);

            RefreshGrid();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            //DateTime mDate = SelectDate.DisplayDate;
            //MessageBox.Show(SelectDate.Text);
            
            // StartSaleUpdate();

            GetListShops();
        }

        void load_Shops(object sender, DownloadStringCompletedEventArgs e)
        {
            list.Clear();
            mFooter = 0;

            if (e.Error != null)
            {
                MessageBox.Show("Error" + e.Error.Message);
                return;
            }

            XDocument grbs = XDocument.Parse(e.Result);
            var query = from g in grbs.Descendants("tbl")
                        select new
                        {
                            //grbId = (int)g.Element("ID"),
                            grbName = (string)g.Element("ShopName"),
                            grbTill1 = (float)g.Element("Till1"),
                            grbTill2 = (float)g.Element("Till2"),
                            grbTill3 = (float)g.Element("Till3"),
                            grbTill4 = (float)g.Element("Till4"),
                            grbTotal = (float)g.Element("Total")

                        };

            foreach (var grb in query)
            {
                AddShop(grb.grbName
                    , (float)grb.grbTill1
                    , (float)grb.grbTill2
                    , (float)grb.grbTill3
                    , (float)grb.grbTill4
                    , (float)grb.grbTotal);
            }

            mainFooter.Text = mFooter.ToString("C");

            //MessageBox.Show("Return " + ms);   
        }

        void AddShop(String mStr, float til1, float til2, float til3, float til4, float total)
        {
            dsData newDataRecord;
            newDataRecord = new dsData();
            newDataRecord.ShopName = mStr;
            newDataRecord.kassa1 = til1;
            newDataRecord.kassa2 = til2;
            newDataRecord.kassa3 = til3;
            newDataRecord.kassa4 = til4;
            newDataRecord.total = total;
            mFooter += total;
            list.Add(newDataRecord);

            RefreshGrid();
        }

        public Color HexColor(String hex)
        {
            //remove the # at the front
            hex = hex.Replace("#", "");

            byte a = 255;
            byte r = 255;
            byte g = 255;
            byte b = 255;

            int start = 0;

            //handle ARGB strings (8 characters long)
            if (hex.Length == 8)
            {
                a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                start = 2;
            }

            //convert RGB characters to bytes
            r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
            g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
            b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);

            return Color.FromArgb(a, r, g, b);
        }

        private void SelectDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            list.Clear();
            mFooter = 0;
            mainFooter.Text = mFooter.ToString("C");
            RefreshGrid();
        }

        private void SelectDate_CalendarClosed(object sender, RoutedEventArgs e)
        {
            list.Clear();
            mFooter = 0;
            mainFooter.Text = mFooter.ToString("C");
            RefreshGrid();
        }

    }
}
